package com.zishuimuyu.job.upload;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.ftp.FtpConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;
import cn.hutool.setting.SettingUtil;
import com.zishuimuyu.mqtt.MyMqttClient;
import com.zishuimuyu.mqtt.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;

/**
 * 定时定时任务任务-只用来上传文件
 *
 * @author：GJH
 * @date
 * @company：北京木联能软件股份有限公司
 */
@Slf4j
public class MqttUploadFileJob {
    private static Setting uploadFileSetting = SettingUtil.getFirstFound("config/uploadFile.setting");
    private static Map<String, String> fileTypes = uploadFileSetting.getMap("fileTypes");
    private static String localPath = "";
    private static String localWeatherPath = "";
    private static String localPowerPath = "";
    private static String remotePath = "";
    private static String remoteWeatherPath = "";
    private static String remotePowerPath = "";
    private static String countFilePath = "";
    private static String filePrefix = "";
    private static String fileExtension = "";
    private static String delete = "";
    @Autowired
    private MyMqttClient myMqttClient;
    /**
     * 发送主题前缀
     */
    @Value("${spring.mqtt.push-topic}")
    private String pushTopic;
    //静态代码块会在依赖注入后自动执行,并优先执行 下载
    static {
        localPath = uploadFileSetting.getStr("localPath");
        localWeatherPath = uploadFileSetting.getStr("localWeatherPath");
        localPowerPath = uploadFileSetting.getStr("localPowerPath");
        remotePath = uploadFileSetting.getStr("remotePath");
        remoteWeatherPath = uploadFileSetting.getStr("remoteWeatherPath");
        remotePowerPath = uploadFileSetting.getStr("remotePowerPath");
        countFilePath = uploadFileSetting.getStr("countFilePath");
        filePrefix = uploadFileSetting.getStr("filePrefix");
        fileExtension = uploadFileSetting.getStr("fileExtension");
        delete = uploadFileSetting.getStr("delete");
    }

    /**
     * 将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行**
     *
     * @Postcontruct’在依赖注入完成后自动调用
     */

    public void upload() {
        log.info("定时任务上传任务启用：{}-> {}", localPath, remotePath);
        String protocol = uploadFileSetting.getStr("protocol");
        String host = uploadFileSetting.getStr("host");
        String charset = uploadFileSetting.getStr("Charset");
        int defaultPort = "sftp".equalsIgnoreCase(protocol) ? 22 : 21;
        Integer port = uploadFileSetting.getInt("port", defaultPort);
        String userName = uploadFileSetting.getStr("userName");
        String passWord = uploadFileSetting.getStr("passWord");
        Long sessionConnectTimeout = uploadFileSetting.getLong("sessionConnectTimeout", 2000L);
        Long channelConnectedTimeout = uploadFileSetting.getLong("channelConnectedTimeout", 2000L);
        FtpConfig ftpConfig = new FtpConfig(host, port, userName, passWord, CharsetUtil.charset(charset));
        ftpConfig.setConnectionTimeout(sessionConnectTimeout);
        ftpConfig.setSoTimeout(channelConnectedTimeout);
        FileUtil.mkdir(localPath);
        FileUtil.mkdir(localWeatherPath);
        FileUtil.mkdir(localPowerPath);
        FileUtil.mkdir(countFilePath);
        List<File> weatherFiles = FileUtil.loopFiles(localWeatherPath);
        List<File> powerFiles = FileUtil.loopFiles(localPowerPath);

        //1.获取创建文件位置
        String path = "E:/back/WPFSData";
        //2.获取备份文件存储的目录
        String dataBackupDir = "/back/WPFSDataBak/";
        File file = FileUtil.file("E:/back/WPFSData", "HA0063_tsi_202411201030.json");
        BufferedReader reader = FileUtil.getReader(file, StandardCharsets.UTF_8);

        try {
            log.info("MQTT开始上传");
            MyMqttClient myMqttClient = SpringContextHolder.getBean(MyMqttClient.class);
            //现在时间
            DateTime now = DateUtil.date();
            String timeSin = DateUtil.format(DateUtil.offsetMinute(now, -2), "yyyyMMdd-HHmm");
            //String yuanShiName = fileNames.stream().filter(s -> s.startsWith(timeSin)).findFirst().orElse("NA");
            //构造json数据
            String type = "filemsg";
            String client_id = "HA0063";
            //name  HA0063_tsi_202411241745.json
            String jsonFileName = client_id + "_tsi_" + DateUtil.format(now, "yyyyMMddHHmm") + ".json";
            String time = DateUtil.formatDateTime(now);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", type);
            jsonObject.put("client_id", client_id);
            jsonObject.put("name", jsonFileName);
            jsonObject.put("time", time);
            //构造 msg
            JSONObject msg = new JSONObject();
            msg.put("type", "tsi");
            msg.put("date", DateUtil.formatDate(now));
            //"TSI-202411241745.jpg"
            msg.put("name", "TSI-" + DateUtil.format(now, "yyyyMMddHHmm") + ".jpg");
            //云量，单位是%
            msg.put("cloud", 99.322678);
            //天气类型
            //0：太阳不可见，1：晴空中现太阳，3：太阳被部分挡住，5：太阳被部分遮挡，但可见光晕，8：太阳不在视场角内
            msg.put("weather", 5);
            //云状
            msg.put("cloud_form", 8);

            msg.put("conver_r", 60.142254);
            msg.put("center_x", 516);
            msg.put("center_y", 540);
            //将文件按转为Base64
            String yuanShiTuPianBase64 = ImgUtil.toBase64(ImgUtil.read(FileUtil.file("E:\\back\\WPFSData","20241126-082631.jpg")), ImgUtil.IMAGE_TYPE_JPG);
            msg.put("data", yuanShiTuPianBase64);
            jsonObject.put("msg", msg);
            log.info("json文件构造完成，发送数据");
            //发文件内容
            //myMqttClient.publish(JSONUtil.toJsonStr(jsonObject), "station/weather");
            log.info("json文件类容发送完成");
            //将json文件写入文件
            FileUtil.writeUtf8String(JSONUtil.toJsonStr(jsonObject), FileUtil.file("E:\\back\\WPFSData", jsonFileName));
            log.info("json数据写入文件完成");

            //发送文件
            //byte[] bytes = FileUtil.readBytes(FileUtil.file(yuanShiWenJanPath, jsonFileName));
            byte[] bytes = Files.readAllBytes(FileUtil.file("E:\\back\\WPFSData", jsonFileName).toPath());
            MqttMessage mqttMessage = new MqttMessage(bytes);
            //String fileContent = FileUtil.readString(FileUtil.file(yuanShiWenJanPath, jsonFileName), StandardCharsets.UTF_8);
            myMqttClient.publish(mqttMessage, "station/weather");
            log.info("json文件发送完成");
            log.info("MqttJob 消息发送成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }





}
